package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.logger.LogMessageType;
import com.conversationboard.model.Log;
import com.conversationboard.model.LogMessage;
import com.conversationboard.model.User;

@WebServlet(name = "AdminShowLogControllerServlet", urlPatterns = "/Admin/AdminShowLogControllerServlet")
public class AdminShowLogControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 6347483410644408199L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			String loginId = request.getUserPrincipal().getName();
			User user = User.get(loginId);

			String type = request.getParameter("type");

			if (!user.isSiteAdmin()) {
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				request.setAttribute("message", "You are not authorised to do that.");
				dispatcher.forward(request, response);
				return;
			}

			List<LogMessage> errors = null;

			if (type.equals("ALL")) {
				errors = Log.getLog();
			} else {
				errors = Log.getLog(LogMessageType.valueOf(type));
			}

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/Admin/log.jsp");
			request.setAttribute("errors", errors);

			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
